package com.zz.framework.widget

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.DashPathEffect
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import androidx.core.view.VelocityTrackerCompat.recycle
import com.google.android.material.button.MaterialButton
import com.zz.framework.R

/**
 * Copyright © 2025 zhun All rights reserved.
 * Created by ZhaoZhun on 2025/2/22 18:24.
 * @author: ZhaoZhun 1820022519@qq.com
 * @version: V1.0
 */
class DashedMaterialButton @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : MaterialButton(context, attrs, defStyleAttr) {

    private var borderColor: Int = Color.GRAY // 默认黑色
    private var borderWidth: Float = 4f // 默认边框宽度
    private var dashWidth: Float = 10f // 默认虚线长度
    private var dashGap: Float = 5f // 默认虚线间隔

    private val paint = Paint().apply {
        style = Paint.Style.STROKE
        isAntiAlias = true
    }

    init {
        context.theme.obtainStyledAttributes(attrs, R.styleable.DashedMaterialButton, 0, 0).apply {
            try {
                borderColor = getColor(R.styleable.DashedMaterialButton_borderColor, Color.BLACK)
                borderWidth = getDimension(R.styleable.DashedMaterialButton_borderWidth, 4f)
                dashWidth = getDimension(R.styleable.DashedMaterialButton_dashWidth, 10f)
                dashGap = getDimension(R.styleable.DashedMaterialButton_dashGap, 5f)
            } finally {
                recycle()
            }
        }
        paint.color = borderColor
        paint.strokeWidth = borderWidth
        paint.pathEffect = DashPathEffect(floatArrayOf(dashWidth, dashGap), 0f)
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        val rect = RectF(borderWidth / 2, borderWidth / 2, width - borderWidth / 2, height - borderWidth / 2)
        canvas.drawRoundRect(rect, 16f, 16f, paint)
    }
}